import jwt
import datetime
from status import *
from django.conf import settings
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework import status


class MYAuthenticationFailed(AuthenticationFailed):
    status_code = status.HTTP_200_OK


class CurrentUser(object):
    def __init__(self, user_id, username, exp):
        self.id = user_id
        self.username = username
        self.exp = exp


def create_token(user_id: int, username: str, expires=settings.TOKEN_EXPIRE) -> str:
    # 构造header
    headers = {
        'typ': 'jwt',
        'alg': 'HS256'
    }
    # 构造payload
    payload = {
        'user_id': user_id,  # 自定义用户ID
        'username': username,  # 自定义用户名
        'exp': datetime.datetime.utcnow() + datetime.timedelta(days=expires)  # 超时时间
    }
    result = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm="HS256", headers=headers)
    return result


class JwtTokenAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        # authorization
        if not token:
            raise MYAuthenticationFailed({"code": AUTH_FAILED, "msg": "认证失败"})
        try:
            payload = jwt.decode(token, settings.SECRET_KEY, ["HS256"])
            return CurrentUser(**payload), token

        except Exception as e:
            return MYAuthenticationFailed({"code": AUTH_FAILED, "msg": "认证失败"})

    def authenticate_header(self, request):
        return 'Bearer realm="API"'
